<?php

namespace App\Http\Controllers\API\Common;

use Config;
use App\Http\Controllers\API\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Facades\Redis;

class ShareController extends ApiController
{
    // 用户退出
    public function signOut(Request $request)
    {
        $token = $request->header('token') ?? '';
        $uid = $request->header('uid') ?? '';

        $redisKey = $uid . '_' . $token;

        if (Redis::exists($redisKey)) {
            Redis::del($redisKey);
        }

        return $this->jsonReturns(10000, $this->success, [], 'signout', trans('alg.Signout-Success'));
    }

    // 图片文件上传
    public function imageUploadStore(Request $request)
    {
        $file = null;
        $tag = null;
        if ($request->hasFile('file')) {
            $file = $request->file('file');
        } elseif ($request->hasFile('images')) {
            $file = $request->file('images');
        } elseif ($request->hasFile('editormd-image-file')) {
            $file = $request->file('editormd-image-file');
            $tag = 'md';
        } elseif ($request->hasFile('image')) {
            $file = $request->file('image');
        }

        // 不存在上传文件信息
        if (is_null($file)) {
            return $this->jsonReturns(50000, trans('The-Empty-File-Error'), [], 'upload/verror', trans('alg.Upload-File-No-File-And-Validate-Error'));
        }

        // 判断文件是否有效
        if (!$file->isValid()) {
            return $this->jsonReturns(50000, trans('The-Upload-File-Is-Not-Valid'), [], 'upload/verror', trans('alg.Upload-File-Not-Valid-And-Validate-Error'));
        }

        // 文件扩展后缀
        $fileExtension = strtolower($file->getClientOriginalExtension());
        if (!in_array($fileExtension, Config::get('api.image_suffix'))) {
            return $this->jsonReturns(50000, trans('The-File-Suffix-Can-Not-Be-Allowed', ['suffix' => $fileExtension]), [], 'upload/verror', trans('alg.Upload-File-Error-Extension-And-Validate-Error'));
        }

        // 判断大小及压缩--TODO

        $tmpFile = $file->getRealPath();
        // 文件上传处理
        $fileName = $this->apiUser['plate_code'] . '/' . date('Y_m_d') . '/' . Uuid::uuid1()->getHex() . '.' . $fileExtension;
        // 文件存储
        if (Storage::disk('uploads')->put($fileName, file_get_contents($tmpFile))) {
            return $this->jsonReturns(10000, $this->success, [
                'storage' => '/uploads/' . $fileName,
                'src' => get_domain(request()->server()) . '/uploads/' . $fileName,
            ], 'upload', trans('alg.Upload-File-Success', ['name' => $fileName]));
        }
    }
}
